import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

import { progressApi } from '@/api/progress'
// import { practiceApi } from '@/api/practice' // 暂时注释，等待新的练习API
import type { SubjectProgress } from '@/http/types'

export interface LearningProgress {
  totalStudyTime: number // 总学习时长(分钟)
  completedQuestions: number // 完成题目数
  masteredTopics: number // 掌握知识点数
  currentStreak: number // 连续学习天数
  accuracy: number // 答题正确率
  lastStudyDate: string | null // 最后学习日期
  weeklyProgress: number[] // 本周学习进度(7天)
  monthlyProgress: number[] // 本月学习进度(30天)
}

export interface StudyRecord {
  id: string
  date: string
  duration: number
  questionsCount: number
  correctCount: number
  topic: string
}

export const useProgressStore = defineStore('progress', () => {
  // 概览进度
  const learningProgress = ref<LearningProgress>({
    totalStudyTime: 0,
    completedQuestions: 0,
    masteredTopics: 0,
    currentStreak: 0,
    accuracy: 0,
    lastStudyDate: null,
    weeklyProgress: [0, 0, 0, 0, 0, 0, 0],
    monthlyProgress: new Array(30).fill(0),
  })

  // 最近学习记录
  const recentActivities = ref<StudyRecord[]>([])

  // 科目进度（与后端结构一致）
  const subjects = ref<
    SubjectProgress | Record<string, { completed: number; total: number; lastStudyTime: string }>
  >({})

  // 练习统计
  const practiceStats = ref<{
    totalPractice: number
    averageScore: number
    totalTime: number
    subjectStats: Record<string, { count: number; averageScore: number }>
  } | null>(null)

  // 加载状态与错误
  const isLoading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isDataLoaded = computed(() => learningProgress.value.totalStudyTime > 0)
  const studyEfficiency = computed(() => {
    if (learningProgress.value.totalStudyTime === 0) return 0
    return Math.round(
      (learningProgress.value.completedQuestions / learningProgress.value.totalStudyTime) * 100,
    )
  })

  // 科目进度列表（便于渲染）
  const subjectList = computed(() => {
    const entries = Object.entries(subjects.value || {})
    return entries.map(([name, s]) => {
      const percent = s.total > 0 ? Math.round((s.completed / s.total) * 100) : 0
      return { name, ...s, percent }
    })
  })

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 获取用户学习进度（聚合：科目进度 + 练习统计 + 最近记录）
  const fetchUserProgress = async (userId: string) => {
    try {
      isLoading.value = true
      clearError()

      // 1) 科目进度
      try {
        const p = await progressApi.getUserProgress(userId)
        if (p?.data?.subjects) {
          subjects.value = p.data.subjects as SubjectProgress
        }
      } catch {}

      // 2) 练习统计
      try {
        // const s = await practiceApi.getPracticeStats(userId) // 暂时注释，等待新的练习API
        // if (s?.data) {
        //   practiceStats.value = s.data
        //   // 用统计补充概览
        //   learningProgress.value.totalStudyTime =
        //     s.data.totalTime || learningProgress.value.totalStudyTime
        //   learningProgress.value.completedQuestions =
        //     s.data.totalPractice || learningProgress.value.completedQuestions
        // }
      } catch {}

      // 3) 最近学习记录
      try {
        // const r = await practiceApi.getUserPracticeRecords(userId) // 暂时注释，等待新的练习API
        // if (Array.isArray(r?.data)) {
        //   recentActivities.value = r.data.map((rec) => ({
        //     id: rec.id,
        //     date: rec.completedAt,
        //     duration: rec.timeSpent,
        //     questionsCount: rec.totalQuestions,
        //     correctCount: rec.correctAnswers,
        //     topic: rec.subject,
        //   }))
        // }
      } catch {}

      // 若仍为空则填充占位数据，保障页面可视化
      if (!learningProgress.value.totalStudyTime) {
        const mockProgress: LearningProgress = {
          totalStudyTime: Math.floor(Math.random() * 1000) + 200,
          completedQuestions: Math.floor(Math.random() * 500) + 50,
          masteredTopics: Math.floor(Math.random() * 20) + 5,
          currentStreak: Math.floor(Math.random() * 30) + 1,
          accuracy: Math.floor(Math.random() * 30) + 70,
          lastStudyDate: new Date().toISOString(),
          weeklyProgress: Array.from({ length: 7 }, () => Math.floor(Math.random() * 120) + 20),
          monthlyProgress: Array.from({ length: 30 }, () => Math.floor(Math.random() * 60) + 10),
        }
        learningProgress.value = mockProgress
      }

      if (recentActivities.value.length === 0) {
        const mockActivities: StudyRecord[] = [
          {
            id: '1',
            date: new Date().toISOString(),
            duration: 45,
            questionsCount: 20,
            correctCount: 18,
            topic: '代数基础',
          },
          {
            id: '2',
            date: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
            duration: 30,
            questionsCount: 15,
            correctCount: 14,
            topic: '几何图形',
          },
          {
            id: '3',
            date: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
            duration: 60,
            questionsCount: 25,
            correctCount: 22,
            topic: '函数与方程',
          },
        ]
        recentActivities.value = mockActivities
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取学习进度失败'
      console.error('Failed to fetch user progress:', err)
    } finally {
      isLoading.value = false
    }
  }

  // 更新学习进度
  const updateProgress = async (data: Partial<LearningProgress>) => {
    try {
      learningProgress.value = { ...learningProgress.value, ...data }
      // 这里应该调用API更新后端数据
      // await progressApi.updateProgress(userStore.user?.id, data)
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新学习进度失败'
      console.error('Failed to update progress:', err)
    }
  }

  // 添加学习记录
  const addStudyRecord = async (record: Omit<StudyRecord, 'id'>) => {
    try {
      const newRecord: StudyRecord = {
        ...record,
        id: Date.now().toString(),
      }

      recentActivities.value.unshift(newRecord)

      // 更新总学习时长
      await updateProgress({
        totalStudyTime: learningProgress.value.totalStudyTime + record.duration,
        completedQuestions: learningProgress.value.completedQuestions + record.questionsCount,
      })
    } catch (err) {
      error.value = err instanceof Error ? err.message : '添加学习记录失败'
      console.error('Failed to add study record:', err)
    }
  }

  // 重置进度数据
  const resetProgress = () => {
    learningProgress.value = {
      totalStudyTime: 0,
      completedQuestions: 0,
      masteredTopics: 0,
      currentStreak: 0,
      accuracy: 0,
      lastStudyDate: null,
      weeklyProgress: [0, 0, 0, 0, 0, 0, 0],
      monthlyProgress: new Array(30).fill(0),
    }
    recentActivities.value = []
    subjects.value = {}
    practiceStats.value = null
  }

  return {
    // 状态
    learningProgress,
    recentActivities,
    subjects,
    practiceStats,
    isLoading,
    error,

    // 计算属性
    isDataLoaded,
    studyEfficiency,
    subjectList,

    // 方法
    fetchUserProgress,
    updateProgress,
    addStudyRecord,
    resetProgress,
    clearError,
  }
})
